package kr.co.redcircle.broker.source;

import kr.co.redcircle.broker.io.IDefaultIO;
import kr.co.redcircle.broker.io.IHandler;
import kr.co.redcircle.broker.registry.Registry;
import kr.co.redcircle.broker.renderer.IRenderer;
import kr.co.redcircle.broker.renderer.JSONResultRenderer;

public abstract class AbstractBrokerSource implements IBrokerSource {

	protected IDefaultIO request = null;
	protected IDefaultIO response = null;
	private IRenderer renderer = new JSONResultRenderer();
	private Object renderResult;
	protected IHandler requestHandler;
	
	public AbstractBrokerSource(IDefaultIO request) {
		super();
		this.request = request;
	}

	public IRenderer getRenderer() {
		return renderer;
	}

	public void setRenderer(IRenderer renderer) {
		this.renderer = renderer;
	}

	public String getResponse(){
		String handlerId = request.getHandler();
		requestHandler = Registry.getHandler(handlerId);
		
		System.out.println("requestHandler : " + handlerId + " , " + requestHandler);
		
		if (requestHandler != null){
			setupPreProcessing();
			execute();
			render();
			setupPostProcessing();
			return renderResult.toString();
		}else{
			return null;
		}
	}

	private void render() {
		this.renderResult = this.renderer.render(this.response);		
	}

	private void execute() {
		executeSource();
	}

	private void setupPreProcessing() {
		preRequestSetup();
		preResponseSetup();
	}

	public abstract void preResponseSetup();

	public abstract void preRequestSetup();
	
	public abstract void executeSource();
	
	public abstract void setupPostProcessing();

}
